package com.be.beadmin.system.impl.ProjectDesignServiceImpl;

import com.be.beadmin.design.entity.BomReview;
import com.be.beadmin.design.entity.BomReviewMain;
import com.be.beadmin.design.entity.ProductBomOverview;
import com.be.beadmin.design.mapper.BomReviewMapper;
import com.be.beadmin.design.mapper.BomReviewMapperEx;
import com.be.beadmin.design.repository.BomReviewMainRepository;
import com.be.beadmin.design.repository.BomReviewRepository;
import com.be.beadmin.design.repository.ProductBomOverviewRepository;
import com.be.beadmin.material.entity.PickingDetails;
import com.be.beadmin.material.entity.PickingTask;
import com.be.beadmin.material.repository.PickingDetailsRepository;
import com.be.beadmin.material.repository.PickingTaskRepository;
import com.be.beadmin.project.entity.BatchProduct;
import com.be.beadmin.project.entity.Info;
import com.be.beadmin.project.entity.TeamInfo;
import com.be.beadmin.project.repository.BatchProductRepository;
import com.be.beadmin.project.repository.InfoRepository;
import com.be.beadmin.project.repository.TeamInfoRepository;
import com.be.beadmin.service.entity.NotifyInfo;
import com.be.beadmin.service.repository.NotifyInfoRepository;
import com.be.beadmin.service.repository.NotifyTemplateInfoRepository;
import com.be.beadmin.service.service.NotifyTemplateInfoService;
import com.be.beadmin.system.service.ProjectDesignSevice.BomReviewPdService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: Mengyang Zhu
 * @Date: 2023/10/3 0:14
 * @Description: BomReviewServiceImpl
 */
@Service
@RequiredArgsConstructor
public class BomReviewPdServiceImpl implements BomReviewPdService {
    @Autowired
    private BomReviewRepository bomReviewRepository;


    @Autowired
    private ProductBomOverviewRepository productBomOverviewRepository;

    @Autowired
    private BatchProductRepository batchProductRepository;


    @Autowired
    private NotifyTemplateInfoService notifyTemplateInfoService;

    @Autowired
    private NotifyTemplateInfoRepository notifyTemplateInfoRepository;

    @Autowired
    private NotifyInfoRepository notifyInfoRepository;
    @Autowired
    private PickingTaskRepository pickingTaskRepository;
    @Autowired
    private PickingDetailsRepository pickingDetailsRepository;

    @Autowired
    private InfoRepository infoRepository;
    @Autowired
    private TeamInfoRepository teamInfoRepository;

    public void confirmBomReview(String id, int reviewState, String memo) throws ParseException {
        BomReview bomReview = bomReviewRepository.findBomReviewByIdAndDelete(id, 0);
        //若通过，生成新的bomOverview
        if (reviewState == 2) {
            String bomOverviewId = bomReview.getBomBeforeId();
            ProductBomOverview productBomOverview = productBomOverviewRepository.findProductBomOverviewByIdAndDelete(bomOverviewId, 0);
            ProductBomOverview bomOverview = new ProductBomOverview();
            if (productBomOverview != null) {

                BeanUtils.copyProperties(productBomOverview, bomOverview);

                bomOverview.setMaterialQty(bomReview.getMaterialQty());
                bomOverview.setVersion(productBomOverview.getVersion() + 1);
                bomOverview.setChangeStatus(1);
                bomOverview.setId(null);
                bomOverview.setCreateId(null);
                bomOverview.setCreateName(null);
                bomOverview.setUpdateId(null);
                bomOverview.setUpdateTime(null);
                bomOverview.setDelete(0);

                productBomOverview.setIsMax(0);
                productBomOverview.setChangeStatus(1);
                productBomOverviewRepository.save(productBomOverview);
            } else {
                BeanUtils.copyProperties(bomReview, bomOverview);
                bomOverview.setChangeStatus(1);
                bomOverview.setId(null);
                bomOverview.setCreateId(null);
                bomOverview.setCreateName(null);
                bomOverview.setUpdateId(null);
                bomOverview.setUpdateTime(null);
                bomOverview.setDelete(0);
            }
            productBomOverviewRepository.save(bomOverview);
            //去更新已生成的分料任务
            PickingTask pickingTask = pickingTaskRepository.findPickingTaskByProjectNameAndProductCodeAndDelete(bomReview.getProjectName(), bomReview.getProductCode(), 0);
            if (pickingTask != null) {
                pickingTask.setPickingState("未分料");
                pickingTaskRepository.save(pickingTask);
                PickingDetails pickingDetails = pickingDetailsRepository.findPickingDetailsByMaterialCodeAndPickingTaskCodeAndPositionNo(bomReview.getMaterialCode(), pickingTask.getPickingTaskCode(), bomReview.getPositionNo());
                if (pickingDetails == null) {
                    //新增details
                    PickingDetails pickingDetails1 = new PickingDetails();
                    BeanUtils.copyProperties(bomReview, pickingDetails1);
                    pickingDetails1.setIsChanged(String.valueOf(1));
                    pickingDetails1.setMemo(null);
                    pickingDetails1.setNotIssuedQty(bomReview.getMaterialQty());
                    pickingDetails1.setCurrentQty(bomReview.getMaterialQty());
                    pickingDetails1.setOutboundQty(0);
                    pickingDetails1.setPickingTaskCode(pickingTask.getPickingTaskCode());
                    pickingDetails1.setWo(pickingTask.getWo());
                    pickingDetails1.setProductCode(pickingTask.getProductCode());
                    pickingDetails1.setProjectName(pickingTask.getProjectName());
                    pickingDetails1.setDeliveryDate(pickingTask.getBatchDeliveryTime());
                    pickingDetailsRepository.save(pickingDetails1);
                } else {
                    int num = bomReview.getMaterialQty();
                    pickingDetails.setMaterialQty(num);
                    pickingDetails.setIsChanged(String.valueOf(1));
                    //如果已发数量大于修改后的需求数量
                    if (pickingDetails.getOutboundQty() > num) {
                        pickingDetails.setOutboundQty(num);
                        pickingDetails.setNotIssuedQty(0);
                    } else {
                        pickingDetails.setNotIssuedQty(num - pickingDetails.getOutboundQty());
                    }
                    pickingDetailsRepository.save(pickingDetails);
                }
            }
            // -------------消息通知------------
            // 审批通过后进行消息通知：技术经理->生产与分料组
            List<String> cateGoryList = Arrays.asList("生产人员", "生产组长", "生产经理", "分料人员", "分料组长", "分料经理");

            BatchProduct product = batchProductRepository.findBatchProductByProductCodeAndDelete(bomReview.getProductCode(), 0);
            NotifyInfo notifyInfo = new NotifyInfo();
            notifyInfo.setModuleName("设计管理");
            notifyInfo.setFuncName("Bom变更");
            notifyInfo.setNotifyDesc("非标柜体编码为[" + product.getProductCode() + "]--Bom变更审批通过");
            notifyInfo.setNotifyType("通知");

            Info projectInfo = infoRepository.findInfoByIdAndDelete(product.getInfoId(), 0);
            TeamInfo teaminfo = teamInfoRepository.findTeamInfoByTeamIdAndCategoryAndDelete(projectInfo.getTeamId(), "技术经理", 0);

            if (teaminfo == null) {
                notifyInfo.setSenderName("-");
            } else {
                notifyInfo.setSenderName(teaminfo.getUserName());
                notifyInfo.setSenderId(teaminfo.getUserId());
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm");
            Date date = new Date();
            notifyInfo.setSendTime(df.parse(df.format(date)));
            notifyInfo = notifyInfoRepository.save(notifyInfo);

            List<TeamInfo> teamList = teamInfoRepository.findTeamInfoByTeamIdAndCategoryInAndDelete(projectInfo.getTeamId(), cateGoryList, 0);
            Set<TeamInfo> sets = new HashSet<>(teamList);
            for (TeamInfo item : sets) {
                notifyTemplateInfoService.sendNotify(notifyInfo, -1, item.getUserName(), item.getUserId());
            }
        } else if (reviewState == 3) {
            // 消息通知： 驳回后技术经理->工程师
            // ---------------------------------------------
            BatchProduct product = batchProductRepository.findBatchProductByProductCodeAndDelete(bomReview.getProductCode(), 0);
            NotifyInfo notifyInfo = new NotifyInfo();
            notifyInfo.setModuleName("设计管理");
            notifyInfo.setFuncName("BOM变更");
            notifyInfo.setNotifyDesc("非柜体编码为[" + product.getProductCode() + "]--BOM变更审批被驳回");
            notifyInfo.setNotifyType("通知");

            Info info = infoRepository.findInfoByIdAndDelete(product.getInfoId(), 0);
            TeamInfo teaminfo = teamInfoRepository.findTeamInfoByTeamIdAndCategoryAndDelete(info.getTeamId(), "技术经理", 0);

            if (teaminfo == null) {
                notifyInfo.setSenderName("-");
            } else {
                notifyInfo.setSenderName(teaminfo.getUserName());
                notifyInfo.setSenderId(teaminfo.getUserId());
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm");
            Date date = new Date();
            notifyInfo.setSendTime(df.parse(df.format(date)));
            notifyInfo = notifyInfoRepository.save(notifyInfo);

            if (product.getEngineer() != null) {
                notifyTemplateInfoService.sendNotify(notifyInfo, -1, product.getEngineer(), null);
            }
        }


        //更新审核的数据
        bomReview.setChangeStatus(reviewState);
        bomReview.setMemo(memo);
        bomReviewRepository.save(bomReview);
    }


    @Autowired
    private BomReviewMainRepository bomReviewMainRepository;


    @Override
    public void confirmBomReviewVersion2(String id, int reviewState, String memo, Integer version, Integer versionSecond, Integer version_pre, Integer versionSecond_pre) throws ParseException {
        List<BomReview> bomReviews = bomReviewRepository.findBomReviewsByReviewMainId(id);

        for(BomReview bomReview : bomReviews) {
            bomReview.setVersion(version);
            bomReview.setVersionSecond(versionSecond);
            bomReviewRepository.save(bomReview);
            confirmBomReview2(bomReview.getId(), reviewState, memo);
        }

        if(reviewState == 2) {
            List<ProductBomOverview> overviews = productBomOverviewRepository.findProductBomOverviewsByProductCodeAndnotequalVersion(bomReviews.get(0).getProductCode(), 0, version_pre, versionSecond_pre);
//        System.out.println(overviews);
//        System.out.println("=============================================================");
            for (ProductBomOverview overview : overviews) {
                if (overview.getChangeStatus() == 0) {
                    ProductBomOverview overviewcopy = new ProductBomOverview();
                    BeanUtils.copyProperties(overview, overviewcopy);
                    overviewcopy.setChangeStatus(0);
                    overviewcopy.setId(null);
                    System.out.println(overviewcopy.getId());
                    overviewcopy.setCreateId(null);
                    overviewcopy.setCreateName(null);
                    overviewcopy.setUpdateId(null);
                    overviewcopy.setUpdateTime(null);
                    overviewcopy.setDelete(0);
                    overviewcopy.setVersion(version);
                    overviewcopy.setVersionSecond(versionSecond);
                    overviewcopy.setIsMax(1);
                    ProductBomOverview save = productBomOverviewRepository.save(overviewcopy);
                }
            }

            for (ProductBomOverview overview : overviews) {
                if (overview.getChangeStatus() == 0) {
                    overview.setIsMax(0);
                    System.out.println(overview.getCreateTime());
                    ProductBomOverview save1 = productBomOverviewRepository.save(overview);
                }
            }
        }

        BomReviewMain bomReviewMain = bomReviewMainRepository.findBomReviewMainByIdAndDelete(id, 0);
        bomReviewMain.setVersion(version);
        bomReviewMain.setVersionSecond(versionSecond);
        bomReviewMain.setChangeStatus(reviewState);
        bomReviewMain.setMemo(memo);
        //bomReviewMain.setChangeSuccess(1);
        bomReviewMainRepository.save(bomReviewMain);
    }


    public void confirmBomReview2(String id, int reviewState, String memo) throws ParseException {
        BomReview bomReview = bomReviewRepository.findBomReviewByIdAndDelete(id, 0);
//        String res = null;
        //若通过，生成新的bomOverview
        if (reviewState == 2) {
            String bomOverviewId = bomReview.getBomBeforeId();
            ProductBomOverview productBomOverview = productBomOverviewRepository.findProductBomOverviewByIdAndDelete(bomOverviewId, 0);
            ProductBomOverview bomOverview = new ProductBomOverview();
            if (productBomOverview != null) {
                BeanUtils.copyProperties(productBomOverview, bomOverview);
                bomOverview.setMaterialQty(bomReview.getMaterialQty());
                bomOverview.setChangeStatus(0);
                bomOverview.setId(null);
                bomOverview.setCreateId(null);
                bomOverview.setCreateName(null);
                bomOverview.setUpdateId(null);
                bomOverview.setUpdateTime(null);
                bomOverview.setDelete(0);

                productBomOverview.setIsMax(0);
                productBomOverview.setChangeStatus(1);
                productBomOverviewRepository.save(productBomOverview);
            } else {
                BeanUtils.copyProperties(bomReview, bomOverview);
                bomOverview.setMaterialQty(bomReview.getMaterialQty());
                bomOverview.setChangeStatus(0);
                bomOverview.setId(null);
                bomOverview.setCreateId(null);
                bomOverview.setCreateName(null);
                bomOverview.setUpdateId(null);
                bomOverview.setUpdateTime(null);
                bomOverview.setDelete(0);
            }
            //if(bomOverview.getMaterialQty() != 0) {
            bomOverview.setVersion(bomReview.getVersion());
            bomOverview.setVersionSecond(bomReview.getVersionSecond());
            ProductBomOverview save = productBomOverviewRepository.save(bomOverview);
            //}
//            res = save.getId();
            //去更新已生成的分料任务
            PickingTask pickingTask = pickingTaskRepository.findPickingTaskByProjectNameAndProductCodeAndDelete(bomReview.getProjectName(), bomReview.getProductCode(), 0);
            if (pickingTask != null) {
                pickingTask.setPickingState("未分料");
                pickingTaskRepository.save(pickingTask);
                PickingDetails pickingDetails = pickingDetailsRepository.findPickingDetailsByMaterialCodeAndPickingTaskCodeAndPositionNo(bomReview.getMaterialCode(), pickingTask.getPickingTaskCode(), bomReview.getPositionNo());
                if (pickingDetails == null) {
                    //新增details
                    PickingDetails pickingDetails1 = new PickingDetails();
                    BeanUtils.copyProperties(bomReview, pickingDetails1);
                    pickingDetails1.setIsChanged(String.valueOf(1));
                    pickingDetails1.setMemo(null);
                    pickingDetails1.setNotIssuedQty(bomReview.getMaterialQty());
                    pickingDetails1.setOutboundQty(0);
                    pickingDetails1.setPickingTaskCode(pickingTask.getPickingTaskCode());
                    pickingDetails1.setWo(pickingTask.getWo());
                    pickingDetails1.setProductCode(pickingTask.getProductCode());
                    pickingDetails1.setProjectName(pickingTask.getProjectName());
                    pickingDetails1.setDeliveryDate(pickingTask.getBatchDeliveryTime());
                    pickingDetailsRepository.save(pickingDetails1);
                } else {
                    int num = bomReview.getMaterialQty();
                    pickingDetails.setMaterialQty(num);
                    pickingDetails.setIsChanged(String.valueOf(1));
                    //如果已发数量大于修改后的需求数量
                    if (pickingDetails.getOutboundQty() > num) {
                        pickingDetails.setOutboundQty(num);
                        pickingDetails.setNotIssuedQty(0);
                    } else {
                        pickingDetails.setNotIssuedQty(num - pickingDetails.getOutboundQty());
                    }
                    pickingDetailsRepository.save(pickingDetails);
                }
            }
            // -------------消息通知------------
            // 审批通过后进行消息通知：技术经理->生产与分料组
            List<String> cateGoryList = Arrays.asList("生产人员", "生产组长", "生产经理", "分料人员", "分料组长", "分料经理");

            BatchProduct product = batchProductRepository.findBatchProductByProductCodeAndDelete(bomReview.getProductCode(), 0);
            NotifyInfo notifyInfo = new NotifyInfo();
            notifyInfo.setModuleName("设计管理");
            notifyInfo.setFuncName("Bom变更");
            notifyInfo.setNotifyDesc("非标柜体编码为[" + product.getProductCode() + "]--Bom变更审批通过");
            notifyInfo.setNotifyType("通知");

            Info projectInfo = infoRepository.findInfoByIdAndDelete(product.getInfoId(), 0);
            TeamInfo teaminfo = teamInfoRepository.findTeamInfoByTeamIdAndCategoryAndDelete(projectInfo.getTeamId(), "技术经理", 0);

            if (teaminfo == null) {
                notifyInfo.setSenderName("-");
            } else {
                notifyInfo.setSenderName(teaminfo.getUserName());
                notifyInfo.setSenderId(teaminfo.getUserId());
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm");
            Date date = new Date();
            notifyInfo.setSendTime(df.parse(df.format(date)));
            notifyInfo = notifyInfoRepository.save(notifyInfo);

            List<TeamInfo> teamList = teamInfoRepository.findTeamInfoByTeamIdAndCategoryInAndDelete(projectInfo.getTeamId(), cateGoryList, 0);
            Set<TeamInfo> sets = new HashSet<>(teamList);
            for (TeamInfo item : sets) {
                notifyTemplateInfoService.sendNotify(notifyInfo, -1, item.getUserName(), item.getUserId());
            }
        } else if (reviewState == 3) {
            // 消息通知： 驳回后技术经理->工程师
            // ---------------------------------------------
            BatchProduct product = batchProductRepository.findBatchProductByProductCodeAndDelete(bomReview.getProductCode(), 0);
            NotifyInfo notifyInfo = new NotifyInfo();
            notifyInfo.setModuleName("设计管理");
            notifyInfo.setFuncName("BOM变更");
            notifyInfo.setNotifyDesc("非柜体编码为[" + product.getProductCode() + "]--BOM变更审批被驳回");
            notifyInfo.setNotifyType("通知");

            Info info = infoRepository.findInfoByIdAndDelete(product.getInfoId(), 0);
            TeamInfo teaminfo = teamInfoRepository.findTeamInfoByTeamIdAndCategoryAndDelete(info.getTeamId(), "技术经理", 0);

            if (teaminfo == null) {
                notifyInfo.setSenderName("-");
            } else {
                notifyInfo.setSenderName(teaminfo.getUserName());
                notifyInfo.setSenderId(teaminfo.getUserId());
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm");
            Date date = new Date();
            notifyInfo.setSendTime(df.parse(df.format(date)));
            notifyInfo = notifyInfoRepository.save(notifyInfo);

            if (product.getEngineer() != null) {
                notifyTemplateInfoService.sendNotify(notifyInfo, -1, product.getEngineer(), null);
            }
        }


        //更新审核的数据
        bomReview.setChangeStatus(reviewState - 1);
        bomReview.setMemo(memo);
        bomReviewRepository.save(bomReview);
//        return res;
    }
}
